<template>
  <div class="queue-query">
    <div class="queue-header">
      <h3>排队查询</h3>
      <div class="controls">
        <el-select 
          v-model="selectedDepartment" 
          placeholder="选择科室" 
          clearable
          @change="filterQueues"
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
        <el-button @click="refreshData">刷新</el-button>
        <el-button type="primary" @click="setReminder">设置提醒</el-button>
      </div>
    </div>
    
    <div class="queue-stats">
      <div class="stat-card">
        <div class="stat-value">{{ totalWaiting }}</div>
        <div class="stat-label">总等待人数</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ avgWaitTime }}</div>
        <div class="stat-label">平均等待时间</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ yourPosition }}</div>
        <div class="stat-label">您的排队位置</div>
      </div>
    </div>
    
    <div class="queue-list">
      <el-table :data="filteredQueues" style="width: 100%">
        <el-table-column prop="department" label="科室" width="180" />
        <el-table-column prop="doctors" label="值班医生" width="180">
          <template #default="scope">
            <el-tag 
              v-for="doctor in scope.row.doctors" 
              :key="doctor" 
              size="small" 
              style="margin-right: 4px;"
            >
              {{ doctor }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="waiting" label="等待人数" width="120">
          <template #default="scope">
            <span :class="{ 'high-waiting': scope.row.waiting > 10 }">
              {{ scope.row.waiting }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="waitTime" label="预计等待时间" width="150" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="takeQueue(scope.row)"
              :disabled="scope.row.userInQueue"
            >
              {{ scope.row.userInQueue ? '已排队' : '排队' }}
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="setReminderForDept(scope.row)"
            >
              提醒
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="queue-tips">
      <el-alert
        title="提示：您可以设置排队提醒，当您的排队位置接近时会收到通知"
        type="info"
        show-icon
        :closable="false"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  ElSelect, 
  ElOption, 
  ElButton, 
  ElTable, 
  ElTableColumn, 
  ElTag, 
  ElAlert, 
  ElMessage, 
  ElLoading 
} from 'element-plus'
import { Refresh, Bell, Ticket } from '@element-plus/icons-vue'
import { useConsultStore } from '@/stores/consult'
import consultApi from '@/api/consult'

// 使用store
const consultStore = useConsultStore()

// 组件状态
const selectedDepartment = ref('')
const filteredQueues = ref([])
const loading = ref(false)
const departments = ref([])
const queueData = ref([])

// 统计数据
const totalWaiting = computed(() => {
  return queueData.value.reduce((sum, item) => sum + (item.waiting || 0), 0)
})

const avgWaitTime = computed(() => {
  if (queueData.value.length === 0) return '0分钟'
  const total = queueData.value.reduce((sum, item) => {
    const minutes = parseInt(item.waitTime) || 0
    return sum + minutes
  }, 0)
  return Math.round(total / queueData.value.length) + '分钟'
})

const yourPosition = computed(() => {
  const queue = queueData.value.find(item => item.userInQueue)
  return queue ? queue.waiting : '未排队'
})

// 初始化数据
onMounted(() => {
  loadDepartments()
  loadQueueData()
})

// 加载科室数据
const loadDepartments = async () => {
  try {
    const result = await consultApi.getDepartments()
    departments.value = result.data || []
  } catch (error) {
    console.error('加载科室数据失败:', error)
    // 使用模拟数据
    departments.value = [
      { id: 1, name: '心内科' },
      { id: 2, name: '急诊科' },
      { id: 3, name: '放射科' },
      { id: 4, name: '检验科' },
      { id: 5, name: '外科' },
      { id: 6, name: '儿科' }
    ]
  }
}

// 加载排队数据
const loadQueueData = async () => {
  loading.value = true
  try {
    const result = await consultApi.getQueueInfo()
    queueData.value = result.map((result, index) => ({
      id: departments.value[index].id,
      department: departments.value[index].name,
      doctors: [`${departments.value[index].name.substring(0,1)}医生`],
      waiting: result.data.queueLength,
      waitTime: `${result.data.waitTime}分钟`,
      userInQueue: Math.random() > 0.8  
    }))
    
    filterQueues() 
  } catch (error) {
    console.error('加载排队数据失败:', error)
    // 使用模拟数据
    queueData.value = [
      { 
        id: 1, 
        department: '心内科', 
        doctors: ['张医生', '李医生'], 
        waiting: 8, 
        waitTime: '25分钟',
        userInQueue: false
      },
      { 
        id: 2, 
        department: '急诊科', 
        doctors: ['王医生'], 
        waiting: 3, 
        waitTime: '10分钟',
        userInQueue: true
      },
      { 
        id: 3, 
        department: '放射科', 
        doctors: ['赵医生', '孙医生', '周医生'], 
        waiting: 15, 
        waitTime: '45分钟',
        userInQueue: false
      },
      { 
        id: 4, 
        department: '检验科', 
        doctors: ['吴医生', '郑医生'], 
        waiting: 12, 
        waitTime: '35分钟',
        userInQueue: false
      },
      { 
        id: 5, 
        department: '外科', 
        doctors: ['刘医生', '陈医生'], 
        waiting: 6, 
        waitTime: '20分钟',
        userInQueue: false
      },
      { 
        id: 6, 
        department: '儿科', 
        doctors: ['杨医生'], 
        waiting: 5, 
        waitTime: '15分钟',
        userInQueue: false
      }
    ]
    filterQueues()
  } finally {
    loading.value = false
  }
}

// 过滤队列
const filterQueues = () => {
  if (!selectedDepartment.value) {
    filteredQueues.value = [...queueData.value]
  } else {
    const deptName = departments.value.find(
      dept => dept.id === selectedDepartment.value
    )?.name
    filteredQueues.value = queueData.value.filter(
      item => item.department === deptName
    )
  }
}

// 刷新数据
const refreshData = () => {
  loadQueueData()
  ElMessage.success('刷新成功')
}

// 取号排队
const takeQueue = async (row) => {
  if (row.userInQueue) {
    ElMessage({ message: '您已在该科室排队', type: 'info' })
    return
  }
  
  try {
    loading.value = true
    // 调用API进行实际排队操作
    await consultApi.submitQueue(row.id)
    
    // 更新用户排队状态
    row.userInQueue = true
    ElMessage({ message: `已成功在${row.department}排队`, type: 'success' })
    
    // 更新store中的排队信息
    consultStore.updateUserQueue(row)
  } catch (error) {
    console.error('排队操作失败:', error)
    ElMessage({ message: '排队操作失败，请重试', type: 'error' })
  } finally {
    loading.value = false
  }
}

// 设置全局提醒
const setReminder = () => {
  ElMessage({ message: '全局提醒功能即将上线', type: 'info' })
}

// 为特定科室设置提醒
const setReminderForDept = (row) => {
  ElMessage({ message: `已设置${row.department}排队提醒`, type: 'success' })
  
  // 更新store中的提醒设置
  consultStore.setQueueReminder(row.id, true)
}
</script>

<style scoped>
.queue-query {
  padding: 20px;
}

.queue-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.queue-header h3 {
  margin: 0;
}

.controls {
  display: flex;
  gap: 12px;
}

.queue-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.high-waiting {
  color: #f56c6c;
  font-weight: bold;
}

.queue-tips {
  margin-top: 20px;
}
</style>